package com.example.quartz.task;

import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.example.quartz.entity.vo.SysMovie;
import com.example.quartz.entity.vo.UpdateMovieSaleVo;
import com.example.quartz.openfeign.MovieSellFeignClient;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 高垚淼
 * @version 1.0
 */
//每天将redis中缓存的售票信息，更新到数据库中，并重新计算排行榜
@Component("PullMovieSellToDatabase")
public class PullMovieSellToDatabase {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    MovieSellFeignClient movieSellFeignClient;

    public void updateMovieSell() {
        try {
            //从数据库中，获取所有电影的id
            List<Integer> ids = (ArrayList<Integer>) movieSellFeignClient.getIds();
            //根据id去redis查询出数据
            for (int id = 0; id < ids.size(); id++) {
                Double price = Double.parseDouble ( ( redisTemplate.opsForValue().get("电影票房：" + ids.get(id))).toString());
                if (Objects.isNull(price)) {
                    continue;
                }
                //执行更新数据库的操作
                movieSellFeignClient.updateMovieSale(new UpdateMovieSaleVo(ids.get(id),price));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
